//
//  AppDelegate.m
//  IMChat
//
//  Created by Admin on 2021/6/18.
//  Copyright © 2021年 TeamOne. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

//应用第一次运行时执行，APP从后台激活不会执行该方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        
   // Override point for customization after application launch.

    //初始化SDK
    [[RCIM sharedRCIM] initWithAppKey:@"bmdehs6pbf59s"];
    
    NSString *userId = [SAMKeychain passwordForService:@"userId" account:AppKey];
    NSString *userPassword = [SAMKeychain passwordForService:@"userPassword" account:AppKey];
    NSString *token = [SAMKeychain passwordForService:@"token" account:AppKey];
    
    //App自启动验证
    if(userId != nil && userPassword != nil && token != nil){
        //验证用户
        [TOAFHttpUtils verifyUserLogin:userId withPassword:userPassword
              withBlock:^(NSString * _Nonnull verifyResult) {
               //验证用户成功
               if([verifyResult isEqualToString:@"success"]){
                   //使用token连接
                   [TORongUtils connectRongIM:token
                     withBlock:^(NSString *connectResult){
                          //token连接成功
                          if([connectResult isEqualToString:@"success"]){
                              
                              // 获取主线程队列
                              dispatch_async(dispatch_get_main_queue(),^{
                                  
                                  /* 使用该方法会导致进去主界面后导航栏消失的问题，查找了很多资料，不知如何解决，但是同样的方法，在LoginViewController内进行模态跳转却不会造成导航栏消失，十分费解～
                                  MainTarBarViewController *mainVC = [[MainTarBarViewController alloc]init];

                                  UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:mainVC];

                                  [self.window.rootViewController presentViewController:mainVC animated:NO completion:nil];
                                  */
                                  
                                  /**Login.storyborad是个历史遗留问题了～
                                   */
                                  //跳转主界面，这个方法会导致login界面一闪而过，但目前找不到其他解法了
                                  LoginViewController *login = (LoginViewController *)[[UIStoryboard storyboardWithName:@"Login" bundle:nil]instantiateInitialViewController];
                                  //将self.window.rootViewController设为LoginViewController
                                  self.window.rootViewController = login;
                                  //直接调用showMainView方法进行主界面显示
                                  [login showMainView];
                                  
                              });
                         }
                    }];
              }
       }];
    }else{
        
        // 获取主线程队列
        dispatch_async(dispatch_get_main_queue(),^{
            
            //用户验证失败，跳转注册登录窗口
            LoginViewController *login = (LoginViewController *)[[UIStoryboard storyboardWithName:@"Login" bundle:nil]instantiateInitialViewController];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
            
            [self.window.rootViewController presentViewController:nav animated:NO completion:nil];
            
        });
        
    }
    
    return YES;
}

//APP挂起时执行，当有电话或者锁屏就会挂起
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

//APP进入后台时执行
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

//APP重新回到前台时执行
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

//APP重新进入活动状态时执行
- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

//APP将要退出时执行
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
    [self saveContext];
}


#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"IMChat"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

//保存数据到持久层
- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
